﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PesticideManage.API.Data;
using PesticideManage.API.Extensions;
using PesticideManage.API.Services.Identity.UserAggregate;
using PesticideManage.Domain.AggregatesModel.PesticideAggregate;

namespace PesticideManage.API.Controllers;
/// <summary>
/// 农药产品管理
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class PesticidesController : ControllerBase
{
    private readonly PesticideContext _context;

    public PesticidesController(PesticideContext context)
    {
        _context = context;
    }

    // GET: api/Pesticides
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Pesticide>>> GetPesticides(int lastId = int.MaxValue)
    {
        // var userName = User.Identity?.Name;
        lastId = lastId == 0 ? int.MaxValue : lastId;
        int userId = User.GetId();
        return await _context.Pesticides
        .AsNoTracking()
        .Where(p => p.UserId == userId && p.Id < lastId)
        .Select(p => new Pesticide { Id = p.Id, Name = p.Name, CreateTime = p.CreateTime, NetContent = p.NetContent, RegistrationNumber = string.Empty })
        .OrderByDescending(p => p.Id)
        .Take(10)
        .ToListAsync();
    }

    // GET: api/Pesticides/5
    [AllowAnonymous]
    [HttpGet("{id}")]
    public async Task<ActionResult<Pesticide>> GetPesticide(int id)
    {
        if (_context.Pesticides == null)
        {
            return NotFound();
        }

        var pesticide = await _context.Pesticides.FirstOrDefaultAsync(p => p.Id == id);

        return pesticide == null ? NotFound() : Ok(pesticide);
    }

    // PUT: api/Pesticides/5
    // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    [HttpPut("{id}")]
    public async Task<IActionResult> PutPesticide(int id, Pesticide pesticide)
    {
        if (id != pesticide.Id)
        {
            return BadRequest();
        }

        pesticide.UserId = User.GetId();
        _context.Pesticides.Update(pesticide);
        await _context.SaveChangesAsync();
        return NoContent();
    }

    // POST: api/Pesticides
    // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
    [HttpPost]
    public async Task<ActionResult<Pesticide>> PostPesticide(Pesticide pesticide)
    {
        if (_context.Pesticides == null)
        {
            return Problem("Entity set 'PesticideContext.Pesticides'  is null.");
        }
        pesticide.UserId = User.GetId();
        if (pesticide.Id != 0)
        {
            pesticide.Name = $"{pesticide.Name}-{pesticide.Id}-复制";
            pesticide.Id = 0;
        }
        _context.Pesticides.Add(pesticide);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetPesticide", new { id = pesticide.Id }, pesticide);
    }
    [HttpPost("pesticides")]
    public async Task<ActionResult<Pesticide>> Posts(Pesticide[] pesticides)
    {
        if (_context.Pesticides == null)
        {
            return Problem("Entity set 'PesticideContext.Pesticides'  is null.");
        }
        _context.Pesticides.AddRange(pesticides);
        await _context.SaveChangesAsync();
        return CreatedAtAction("GetPesticides", null);
    }
    // DELETE: api/Pesticides/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeletePesticide(int id)
    {
        if (_context.Pesticides == null)
        {
            return NotFound();
        }
        var pesticide = await _context.Pesticides.FindAsync(id);
        if (pesticide == null)
        {
            return NotFound();
        }

        _context.Pesticides.Remove(pesticide);
        await _context.SaveChangesAsync();

        return NoContent();
    }

    private bool PesticideExists(int id)
    {
        return (_context.Pesticides?.Any(e => e.Id == id)).GetValueOrDefault();
    }
}
